<template>
  <div class="flex flex-col h-full">
    <div class="flex-1 overflow-auto">
      <a-form ref="formRef" :model="formState" :label-col="{ style: { width: '100px' } }" class="mt-4 form-style-flex">
        <a-form-item name="appDeptCode" label="预约科室" class="w-1/3" v-bind="validateInfos.appDeptCode">
          <!-- <SelectSection v-model:value="formState.appDeptCode" :search-params="{ yxzt: '0' }" @change="getDepositPrice" /> -->
          <!-- <SelectRegistrationDepart v-model:value="formState.appDeptCode" :search-params="{ sfylks: '0' }" @change="getDepositPrice" /> -->
          <a-select
            v-model:value="formState.appDeptCode"
            placeholder="请选择"
            :options="departmentList"
            :field-names="{ label: 'ksmc', value: 'ksdm' }"
            @select="getDepositPrice"
          />
        </a-form-item>
        <a-form-item name="wardId" label="预约病区" class="w-1/3" v-bind="validateInfos.wardId">
          <!-- <SelectArea v-model:value="formState.wardId" allow-clear @change="handlerSelectArea" /> -->
          <a-select
            v-model:value="formState.wardId"
            :options="wardList"
            :field-names="{ label: 'wardName', value: 'id' }"
            placeholder="请选择"
            @change="handlerSelectArea"
          />
        </a-form-item>
        <a-form-item name="wardId" label="护理等级" class="w-1/3" v-bind="validateInfos.lastNurseLevelId">
          <SelectLevel v-model:value="formState.lastNurseLevelId" trigger="init" />
        </a-form-item>
        <a-form-item name="bedCode" label="目标床位" class="w-1/3">
          <!-- <a-input v-model:value="formState.bedCode" placeholder="请输入" /> -->
          <SelectTable
            v-model:value="formState.bedCode"
            type="床位"
            :placeholder="formState.wardId ? '请选择' : '请选择病区'"
            :disabled="!formState.wardId"
            :search-params="{ bqid: formState.wardId }"
            :row-disabled="(row) => row.status === 2 || row.status === 1"
            @select="onSelectWard"
          />
        </a-form-item>
        <a-form-item name="dictItemName" label="入院途径" class="w-1/3" v-bind="validateInfos.dictItemName">
          <SelectItem v-model:value="formState.dictItemName" type="DT00013" trigger="focus" placeholder="请选择" @select="selectDict($event)" />
        </a-form-item>
        <a-form-item name="bw" label="部位" class="w-1/3" v-bind="validateInfos.bw">
          <!-- <a-select v-model:value="formState.bw" placeholder="请选择" mode="multiple" :max-tag-count="3" :options="positionList" allow-clear /> -->
          <SelectPartTags
            :value="{ partCode: formState.bw, partName: formState.bws }"
            multiple
            allow-clear
            show-new
            :input-or-textarea="true"
            type="部位"
            @select=";(formState.bw = $event?.partCode), (formState.bws = $event?.partName)"
          />
        </a-form-item>
        <a-form-item label="医疗类别" class="w-1/3" name="inpTypeCode" v-bind="validateInfos.inpTypeCode">
          <SelectItem v-model:value="formState.inpTypeCode" type="med_type" :params="{ type: '住院' }" trigger="init" placeholder="请选择" />
        </a-form-item>
        <a-form-item label="付费方式" name="paymentTypeCode" class="w-1/3">
          <SelectItem
            v-model:value="formState.paymentTypeName"
            type="DT00289"
            trigger="init"
            placeholder="请选择"
            @change="
              (_, $event) => {
                formState.paymentTypeCode = $event.value
                formState.paymentTypeName = $event.label
              }
            "
          />
        </a-form-item>
        <a-form-item name="dutyDoctorName" label="责任医生" class="w-1/3">
          <SelectTable v-model:value="formState.dutyDoctorName" type="医生" placeholder="请选择" allow-clear @select="onSelect($event, 'dutyDoctor')" />
        </a-form-item>
        <a-form-item name="inpDoctorName" label="住院医生" class="w-1/3">
          <SelectTable v-model:value="formState.inpDoctorName" type="医生" placeholder="请选择" allow-clear @select="onSelect($event, 'inpDoctor')" />
        </a-form-item>
        <a-form-item name="attendingDoctorName" label="主治医生" class="w-1/3">
          <SelectTable
            v-model:value="formState.attendingDoctorName"
            type="医生"
            placeholder="请选择"
            allow-clear
            @select="onSelect($event, 'attendingDoctor')"
          />
        </a-form-item>
        <a-form-item name="directorDoctorName" label="主任(副)医生" class="w-1/3">
          <SelectTable v-model:value="formState.directorDoctorName" type="医生" allow-clear placeholder="请选择" @select="onSelect($event, 'directorDoctor')" />
        </a-form-item>
        <a-form-item v-if="!isArmy" name="dpJe" label="押金" class="w-1/3">
          <a-input v-model:value="formState.dpJe" v-input:int placeholder="请输入" @blur="onBlurPrice" />
        </a-form-item>
        <a-form-item label="入院诊断" :class="!isArmy ? 'w-2/3' : 'w-full'" v-bind="validateInfos.outpIco10codeName">
          <a-input-group compact>
            <SelectTable
              v-model:value="formState.outpIco10codeName"
              type="诊断"
              class-name="!w-3/4"
              placeholder="请选择"
              @clear="formState.outpIco10code = ''"
              @select="admissionAiagnosis"
            />
            <a-input v-model:value="formState.outpIco10code" class="!w-1/4" placeholder="诊断代码" disabled />
          </a-input-group>
        </a-form-item>
        <a-form-item name="expectDays" label="预计住院天数" class="w-1/3">
          <a-input v-model:value="formState.expectDays" placeholder="请输入" />
        </a-form-item>
        <a-form-item name="readyOperation" label="行何手术" class="w-2/3">
          <a-input v-model:value="formState.readyOperation" placeholder="请输入" />
        </a-form-item>
        <a-form-item name="brLxr" label="联系人" class="w-1/3">
          <a-input v-model:value="formState.brLxr" placeholder="请输入" />
        </a-form-item>
        <a-form-item name="brLxrgx" label="联系人关系" class="w-1/3">
          <SelectItem v-model:value="formState.brLxrgx" type="DT00008" value-key="dictItemName" placeholder="请选择" />
        </a-form-item>
        <a-form-item name="brLxrdh" label="联系人电话" class="w-1/3">
          <a-input v-model:value="formState.brLxrdh" placeholder="请输入" />
        </a-form-item>
        <a-form-item name="brGms" label="过敏史" class="w-full">
          <SelectAllergyModal
            v-model:value="formState.brGms"
            :br-id="formState.brId"
            :source-data="formState.patientAllergys"
            @success="formState.patientAllergys = $event.data"
          />
        </a-form-item>
        <!-- patientAllergys -->
        <a-form-item name="brYcs" label="遗传史" class="w-full">
          <a-input v-model:value="formState.brYcs" placeholder="请输入" />
        </a-form-item>
        <a-form-item name="memo" label="说明" class="w-full">
          <a-textarea v-model:value="formState.memo" :rows="15" placeholder="请输入" />
        </a-form-item>
      </a-form>
    </div>
    <a-space class="flex justify-between h-10">
      <div v-if="wardInfo?.wardBedInfo" class="ml-10">
        <span>总床位：{{ wardInfo?.wardBedInfo?.total || '-' }}</span>
        <span class="inline-block ml-2">已用床位：{{ wardInfo?.wardBedInfo?.usedNum || '-' }}</span>
        <span class="inline-block ml-2">空余床位：{{ wardInfo?.wardBedInfo?.idleNum || '-' }}</span>
        <span class="inline-block ml-2">入院申请：{{ wardInfo?.wardBedInfo?.applyNum || '-' }}</span>
      </div>
      <div v-else></div>
      <a-space class="flex">
        <div class="absolute top-[-9999px] hidden">
          <a-button ref="printMe" v-print="{ id: 'printMe' }">打印</a-button>
          <PrintView id="printMe" :print-data="printData" />
        </div>
        <a-button :disabled="!isCompleted || formatBw()" @click="onPrint">打印</a-button>
        <a-button @click="getData">重置</a-button>
        <a-button type="primary" :disabled="!isCompleted || formatBw()" @click="saveData">保存</a-button>
      </a-space>
    </a-space>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { post, get } from '@/utils/request'
// import SelectTable from '@/components/SelectTable'
// import SelectArea from '@/components/SelectArea'
import SelectTable from '@/components/SelectTable'
import userStore from '@/store/user'
import { getSystemConfig } from '@/utils/systemConfig'
import SelectAllergyModal from '@/components/SelectAllergy'

const { empId, empName } = userStore()
import useStore from '../../store'
import PrintView from './PrintView.vue'

const isArmy = getSystemConfig('NAVYHIS_MODE') === '1' //军用系统
const bwMust = getSystemConfig('INP_ADMISSION_REGISTRATION_MUST_CHOOSE_PART') === '1' //入院申请及登记时部位必选
const store = useStore()
const formRef = ref(null)
const printData = ref({})
const printMe = ref()
const formState = ref({
  bw: [],
  appDeptCode: null,
  lastNurseLevelId: getSystemConfig('INP_DEFAULT_NURSE_LENVEL_CODE'),
  wardId: null,
  dutyDoctor: empId,
  dutyDoctorName: empName,
  inpDoctorName: null,
  attendingDoctorName: null,
  directorDoctorName: null,
  outpIco10codeName: null,
  dictItemName: null
})
const wardList = ref([])
const depositPrice = ref(0)
const rulesState = ref({
  // paymentTypeCode: [{ required: true, message: '请选择付费方式' }],
  inpTypeCode: [{ required: true, message: '请选择医疗类别' }],
  appDeptCode: [{ required: true, message: '请选择预约科室' }],
  wardId: [{ required: true, message: '请选择预约病区' }],
  // dutyDoctorName: [{ required: true, message: '请选择责任医生' }],
  outpIco10codeName: [{ required: true, message: '请选择入院诊断' }],
  dictItemName: [{ required: true, message: '请选择入院途径' }],
  bw: [{ required: bwMust ? true : false, message: '请选择部位' }],
  lastNurseLevelId: [{ required: true, message: '请选择护理等级' }]
})
const { isCompleted, validateInfos } = useForm(formState, rulesState)
// 员工信息（拿登录人科室）
const getEmpInfo = async () => {
  const { code, data, msg } = await get('/common/emp/getEmpInfo?empid=' + empId)
  if (code !== 0) return message.error(msg)
  formState.value.appDeptCode = data.ksdm
}

const handlerSelectArea = () => {
  formState.value.bedCode = null
  getWardInfo()
}
const wardInfo = ref({})
const getWardInfo = async () => {
  if (!formState.value.wardId) return
  const { code, data, msg } = await post('/inp/inpComprehensive/getWardResponse', {
    wardId: formState.value.wardId
  })
  if (code !== 0) return message.error(msg || '获取数据失败')
  wardInfo.value = data || {}
}

//获取数据
const getData = async () => {
  const { data, code, msg } = await post('/inp/zydj/getInpAppointmentRecord', {
    jzbh: store.currentPatient.jzbh //就诊编号
  })
  if (code !== 0) return message.error(msg)
  if (data) {
    formState.value = data
    formState.value.bw = data.bw ? data.bw : undefined
  } else {
    formRef.value.resetFields()
    formState.value.outpIco10code = ''
    formState.value.wardId = null
    getEmpInfo()
  }
  formState.value.outpIco10codeName = data?.outpIco10codeName || store.currentMedical?.bcLczdZdmc
  formState.value.outpIco10code = data?.outpIco10code || store.currentMedical?.bcLczdZddm
  getDefaultDictItem()
}

const getDepositPrice = async () => {
  const { data, code, msg } = await post('/operation/opex/getInpDeptDepositSetList', {
    mcbh: '',
    ksdm: formState.value.appDeptCode
  })
  if (code !== 0) return message.error(msg)
  if (data) {
    depositPrice.value = data[0].depositLimit
  }
}

const saveData = async () => {
  const { code, msg } = await post('/inp/zydj/doSaveInpAppointmentRecord', {
    ...formState.value,
    brId: store.currentPatient.brId,
    keycode: store.currentPatient.jzbh,
    outpDoctor: empId
  })
  if (code !== 0) return message.error(msg || '入院申请失败')
  message.success(msg)
  getData()
}
const onSelect = (select, key) => {
  formState.value[key] = select.empId || ''
  formState.value[key + 'Name'] = select.empName || ''
}
const onSelectWard = (select) => {
  formState.value.bedCode = select.bedCode
}

const admissionAiagnosis = (select) => {
  formState.value.outpIco10codeName = select.zdmc
  formState.value.outpIco10code = select.nmiIcd10Code
  formState.value.outpZddm = select.zddm
}
const selectDict = (val) => {
  formState.value.admissionRoadCode = val
}

const onBlurPrice = () => {
  if (formState.value.appDeptCode && depositPrice.value) {
    if (Number(depositPrice.value) > Number(formState.value.depositAmount)) {
      message.error('不可低于押金下限')
      formState.value.depositAmount = ''
    }
  }
}

// 获取预约病区
const getWardData = async () => {
  const { code, data } = await post('/operation/opex/getWardInfoList', { wardTypeCodes: ['QYLB001'] })
  if (code !== 0) return message.error(code)
  wardList.value = data
}
// 获取默认入院途径  默认选中门诊
const getDefaultDictItem = async () => {
  const { data = [], code } = await post('/operation/opex/getDictCommonItemList', { dictCommonCode: 'DT00013', status: 1 })
  if (code === 0 && data.length > 0) {
    const outData = data.filter((item) => {
      return item.dictItemName.includes('门诊')
    })
    if (outData && outData.length > 0) {
      formState.value.dictItemName = outData[0].dictItemName
      formState.value.admissionRoadCode = outData[0].dictItemCode
    }
  }
}

// 获取科室
const departmentList = ref([])
const getDepartmentList = async () => {
  const { code, data } = await post('/outp/mzdj/getDeptInfoList', { sfylks: '0' })
  if (code !== 0) return
  departmentList.value = data
}

// 打印
const onPrint = async () => {
  // 输入型0:通用|1：住院证
  if (getSystemConfig('INP_NOTICE_DOCUMENT_MODE') === '1') {
    const { code, msg, data } = await post('/inp/Print/hospitalizationCertificatePrint', { jzbh: store.currentPatient.jzbh })
    if (code !== 0) return message.error(msg)
    window.openExe?.rpt(data) //调用winform打印
  } else {
    const { code, msg, data } = await post('/inp/Print/hospitalizationNoticesPrint', { jzbh: store.currentPatient.jzbh })
    if (code !== 0) return message.error(msg)
    if (isArmy) {
      printData.value = JSON.parse(data)
      setTimeout(() => {
        setPrintSize('A5', 'landscape')
        printMe.value.$el.click()
      }, 1000)
    } else {
      window.openExe?.rpt(data) //调用winform打印
    }
  }
}
const formatBw = () => {
  if (bwMust) {
    return !formState.value.bw?.length
  } else {
    return false
  }
}

onMounted(() => {
  getData()
  getWardData()
  getDepartmentList()
})
</script>
<style lang="less" scoped>
.ant-col {
  padding-right: 0 !important;
}
.ant-row {
  margin-right: 0 !important;
}
</style>
